﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.Utlis.Extend
{
    public static class BytesExtend
    {
        /// <summary>
        /// 拷贝长度
        /// </summary>
        /// <param name="sourceBytes"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static Byte[] Copy(this Byte[] sourceBytes, int length)
        {
            Byte[] resultBytes = new byte[length];
            Buffer.BlockCopy(sourceBytes, 0, resultBytes, 0, length);
            return resultBytes;
        }

        public static string Print(this Byte[] sourceBytes)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var tmp in sourceBytes)
            {
                sb.Append(tmp).Append(" ");
            }
            return sb.ToString();
        }

        /// <summary>
        /// 拷贝长度
        /// </summary>
        /// <param name="sourceBytes"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static Byte[] Copy(this Byte[] sourceBytes, int startIndex, int length)
        {
            Byte[] resultBytes = new byte[length];
            Buffer.BlockCopy(sourceBytes, startIndex, resultBytes, 0, length);
            return resultBytes;
        }

        public static void Copy(this Byte[] sourceBytes, ref Byte[] resultBytes)
        {
            Buffer.BlockCopy(sourceBytes, 0, resultBytes, 0, resultBytes.Length);
        }

        public static Byte[] Mergin(this Byte[] headBytes, ref Byte[] bytes)
        {
            Byte[] resultBytes=new byte[headBytes.Length+ bytes.Length];
            Buffer.BlockCopy(headBytes, 0, resultBytes, 0, headBytes.Length);//这种方法仅适用于字节数组
            Buffer.BlockCopy(bytes, 0, resultBytes, headBytes.Length, bytes.Length);
            return resultBytes;
        }

       public static byte SetHigh4Bits(this byte original, byte newHigh)
        {
            // 确保输入值在0-15范围内（4位）
            newHigh = (byte)(newHigh & 0x0F);
            return (byte)((original & 0x0F) | (newHigh << 4));
        }

       public static byte SetLow4Bits(this byte original, byte newLow)
        {
            // 确保输入值在0-15范围内
            newLow = (byte)(newLow & 0x0F);
            return (byte)((original & 0xF0) | newLow);
        }
    }
}
